<template>
  <WorkflowVue
    ref="workflowRef"
    main-height="calc(100vh - 148px)"
    :mapPicture="mapPicture"
    :isCanvasEdit="isCanvasEdit"
    :groupDataList="groupDataList"
    @subGroupData="subGroupData"
    @DeletePartitionDataFun="DeletePartitionDataFun"
  >
    <template #btn>
      <div class="class-view">
        <div v-if="mapInfo" class="name">模块名称: {{ mapInfo.modelName }}</div>
        <div v-if="mapInfo" class="name">
          模块应用: {{ mapInfo.applicationType }}
        </div>
        <div v-if="mapInfo" class="name">
          模块属性: {{ mapInfo.moduleType }}
        </div>
      </div>
      <div class="set-btn">
        <n-upload
          v-if="isCanvasEdit"
          :show-file-list="false"
          :custom-request="customRequest"
          accept="image/png, image/jpeg,image/webp"
        >
          <div class="btn import" size="small">导入</div>
        </n-upload>
        <div
          v-if="isCanvasEdit"
          class="btn pre"
          size="small"
          @click="updateConfig(false)"
        >
          预览
        </div>
        <div
          v-if="superUser < 2 && !isCanvasEdit"
          class="btn"
          size="small"
          @click="updateConfig(true)"
        >
          编辑
        </div>
        <div v-if="isCanvasEdit" class="btn" size="small" @click="saveConfig">
          保存
        </div>
      </div>
    </template>
  </WorkflowVue>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from "vue";
import { UploadCustomRequestOptions } from "naive-ui";
import { useRoute } from "vue-router";
import { uuid } from "@/tools/radom";
import WorkflowVue from "../../packages";
import {
  GetPageInitData,
  GetFirstType,
  GetSecondType,
  InsertOrUpdateMapPicture,
  UploadFile,
  GetBindData,
  InsertBindData,
  InsertOrUpdatePartitionData,
  GetPartitionData,
  DeletePartitionData,
} from "@/server";
import { useAppStore } from "@/store/modules/user";
import { mapStore } from "@/store/modules/map";
const route = useRoute();
const modelId = computed(() => route.params.id);
const store = useAppStore();
const superUser = computed(() => store.superUser);
const mapData = mapStore();
const workflowRef = ref();
const mapPicture = ref("");
const mapInfo = ref(null) as any;
const groupDataList = ref([]) as any;
const postion = ref([]) as any;
const mapDataList = ref([]) as any;
//获取初始化数据
const GetPageInitDataFun = async () => {
  const res: any = await GetPageInitData({ modelId: modelId.value });
  if (res.result.isSuccess) {
    mapInfo.value = res.result.result;
  } else {
    store.error(res.result.message); // 错误提示
  }
};

//获取一级菜单
const GetFirstTypeFun = async () => {
  const res: any = await GetFirstType({ pageNumber: 1, pageSize: 1000 });
  if (res.result.isSuccess) {
    mapData.setFirstData(res.result.result);
    GetSecondTypeFun(res.result.result[0].id);
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取二级菜单
const GetSecondTypeFun = async (parentId: number) => {
  const res: any = await GetSecondType({
    parentId: parentId,
    pageNumber: 1,
    pageSize: 1000,
  });
  if (res.result.isSuccess) {
    mapData.setSecondData(res.result.result);
  } else {
    store.error(res.result.message); // 错误提示
  }
};
watch(
  () => modelId.value,
  async () => {
    await GetPartitionDataFun();
    GetPageInitDataFun();
    GetFirstTypeFun();
    GetBindDataFun();
  }
);
onMounted(async () => {
  await GetPartitionDataFun();
  GetPageInitDataFun();
  GetFirstTypeFun();
  GetBindDataFun();
  // GetSecondTypeNameFun();
});
const isCanvasEdit = ref(false); //默认不是编辑模式
const updateConfig = (type: boolean) => {
  isCanvasEdit.value = type;
};
const customRequest = async ({ file }: UploadCustomRequestOptions) => {
  const formData = new FormData();
  if (file && file.type) {
    const fileName = file.name;
    const fileExtension = fileName.split(".").pop();
    const randomSuffix = uuid();
    // 构建新文件名
    const newFileName = `${randomSuffix}.${fileExtension}`;
    // 创建一个新的File对象，用新文件名替换原文件名
    formData.append("file", file.file as File, newFileName);
    // 创建一个新Blob对象，将文件内容复制到其中
    const res: any = await UploadFile(formData);
    if (res.result.isSuccess) {
      const imgUrl = res.result.result.fileName; //图片上传的路径
      InsertOrUpdateMapPictureFun(imgUrl);
    } else {
      store.error(res.result.message); // 错误提示
    }
  }
};
//上传背景图
const InsertOrUpdateMapPictureFun = async (mapPicture: string) => {
  const res: any = await InsertOrUpdateMapPicture({
    modelId: modelId.value,
    mapPicture: mapPicture,
  });
  if (res.result.isSuccess) {
    GetBindDataFun();
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取绑定数据
const GetBindDataFun = async () => {
  const res: any = await GetBindData({
    modelId: modelId.value,
  });
  if (res.result.isSuccess) {
    mapPicture.value = res.result.result.mapPicture;
    mapDataList.value = res.result.result.data;
    postion.value = JSON.parse(res.result.result.position);
    initData();
  } else {
    store.error(res.result.message); // 错误提示
  }
};

//获取分组数据
const GetPartitionDataFun = async (type?: boolean) => {
  const res: any = await GetPartitionData({
    mapId: modelId.value,
  });
  if (res.result.isSuccess) {
    groupDataList.value = res.result.result;
    if (type) {
      initData();
    }
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//保存分组
const subGroupData = async (data: any) => {
  data.partition.mapId = modelId.value;
  const params = {
    datas: [data],
  };
  const res: any = await InsertOrUpdatePartitionData(params);
  if (res.result.isSuccess) {
    GetPartitionDataFun(true);
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const DeletePartitionDataFun = async (id: any) => {
  const res: any = await DeletePartitionData({ id });
  if (res.result.isSuccess) {
    GetPartitionDataFun(true);
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const saveConfig = async () => {
  const mapData = workflowRef.value?.getData();
  console.log(JSON.stringify(mapData));

  const filterText = JSON.parse(JSON.stringify(mapData))
    .filter((e: any) => e.displayName !== "text")
    .map((e: any) => {
      delete e.dataList;
      delete e.border;
      delete e.partitionId;
      return e;
    });
  let isNull = false;
  const params = {
    modelId: modelId.value,
    position: JSON.stringify(mapData),
    bindData: filterText.map((e: any) => {
      if (!e.displayName) {
        isNull = true;
      }
      return {
        secondId: e.name,
        processName: e.displayName,
        data: e.props
          .filter((e: any) => e.checked)
          .map((e: any) => {
            return {
              bindData: e.propertyName,
              chartType: e.chartType,
            };
          }),
      };
    }),
  };
  if (isNull) {
    store.error("请选择节点属性"); // 错误提示
    return false;
  }
  const res: any = await InsertBindData(params);
  if (res.result.isSuccess) {
    isCanvasEdit.value = false;
    GetBindDataFun();
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const initData = () => {
  console.log(JSON.stringify(postion.value));
  const list = postion.value.map((e: any) => {
    delete e.border;
    delete e.partitionId;
    const item = mapDataList.value.find(
      (m: any) => m.processName === e.displayName && m.secondPicture === e.img
    );

    if (item) {
      e.dataId = item.id;
      e.dataList = item.dataList;
    }
    for (let index = 0; index < groupDataList.value.length; index++) {
      const element = groupDataList.value[index];
      element.models.find((c: any) => {
        if (c.modelId === e.dataId) {
          e.border = element.color;
          e.partitionId = c.partitionId;
        }
      });
    }
    return e;
  });
  workflowRef.value?.setData(list);
};
</script>

<style lang="less" scoped>
.class-view {
  display: flex;
  align-items: center;
  .name {
    font-size: 18px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #1c262d;
    line-height: 25px;
    margin-right: 20px;
    min-width: 150px;
  }
}
// 开始结束按钮
.icon-circle {
  border-radius: 50%;
  border: none;

  &.start {
    background: radial-gradient(circle at 70px 70px, #00b289, #eee);
  }

  &.end {
    background: radial-gradient(circle at 70px 70px, #fe6752, #eee);
  }
}
</style>
